package com.boesch.electroOffice.dataaccess.daoImpl;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.boesch.electroOffice.dataaccess.common.IllegalDataAccessException;
import com.boesch.electroOffice.dataaccess.common.ReturnCodesDataaccess;
import com.boesch.electroOffice.dataaccess.dao.IdentifierDao;
import com.boesch.electroOffice.dataaccess.dao.ToolsHistoryDao;
import com.boesch.electroOffice.dataaccess.mapper.ToolsMapper;
import com.boesch.electroOffice.model.electroOffice.Tool;
import com.boesch.electroOffice.utils.DateUtils;
import com.boesch.electroOffice.utils.UserUtils;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.model.User;

/**
 * This class executes the sql statements on the database for class ToolsHistory.
 * If a Exception is thrown, 
 * it will be unpacked to a illegalDataAccessException 
 * including a return code which can be shown to the user.
 * 
 * @author Ralph Koster
 * 
 */
public class ToolsHistoryDaoImpl implements ToolsHistoryDao, Serializable {

	private static final long serialVersionUID = 6301644099277773451L;
	private static final Log log = LogFactoryUtil.getLog(ToolsHistoryDaoImpl.class);

	@Autowired
	private IdentifierDao identifierDao;
	@Autowired
	private JdbcTemplate eoJdbcTemplate;

	@Value("${electroOffice.queryCreateToolHistory}")
	private String queryCreateToolHistory;
	@Value("${electroOffice.queryReadToolHistoriesByToolId}")
	private String queryReadToolHistoriesByToolId;
	@Value("${electroOffice.queryReadToolHistoriesByInternalNumber}")
	private String queryReadToolHistoriesByInternalNumber;
	@Value("${electroOffice.queryReadToolHistoriesByEntityAndIdentifier}")
	private String queryReadToolHistoriesByEntityAndIdentifier;

	/**
	 * {@inheritDoc}
	 */
	public String createToolHistory(final Tool tool) throws IllegalDataAccessException {
		KeyHolder keyHolder = new GeneratedKeyHolder();
		final User currentUser = UserUtils.getCurrentUser();
		try {
			eoJdbcTemplate.update(new PreparedStatementCreator() {
				public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
					PreparedStatement ps = connection.prepareStatement(queryCreateToolHistory, Statement.RETURN_GENERATED_KEYS);
					ps.setInt(1, tool.getId());
					ps.setString(2, tool.getName());
					ps.setString(3, tool.getType());
					ps.setString(4, tool.getDescription());
					ps.setString(5, tool.getManufacturer());
					ps.setString(6, tool.getInternalNumber());
					ps.setInt(7, tool.getAppointmentId());
					ps.setLong(8, tool.getLrUserId());
					ps.setInt(9, null != tool.getToolIdentifier() ? tool.getToolIdentifier().getId() : null);
					ps.setString(10, currentUser.getFullName());
					ps.setTimestamp(11, DateUtils.getCurrentTimestamp());
					ps.setInt(12, 1);
					return ps;
				}
			}, keyHolder);
			log.debug("Inserted toolHistory with id: " + keyHolder.getKey());
			return ReturnCodesDataaccess.CREATED.getValue();
		} catch (DataAccessException e) {
			throw new IllegalDataAccessException(ReturnCodesDataaccess.CREATION_ERROR.getValue(), e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public List<Tool> readToolHistoriesByToolId(int toolId) throws IllegalDataAccessException {
		List<Tool> tools = new ArrayList<Tool>();
		try {
			tools = eoJdbcTemplate.query(queryReadToolHistoriesByToolId, new Object[] { toolId }, new ToolsMapper(identifierDao));
			return tools;
		} catch (DataAccessException e) {
			throw new IllegalDataAccessException(ReturnCodesDataaccess.NO_OBJECTS_FOUND_ERROR.getValue(), e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public List<Tool> readToolHistoriesByInternalNumber(String internalNumber) throws IllegalDataAccessException {
		List<Tool> tools = new ArrayList<Tool>();
		try {
			tools = eoJdbcTemplate.query(queryReadToolHistoriesByInternalNumber, new Object[] { internalNumber }, new ToolsMapper(identifierDao));
			return tools;
		} catch (DataAccessException e) {
			throw new IllegalDataAccessException(ReturnCodesDataaccess.NO_OBJECTS_FOUND_ERROR.getValue(), e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public List<Tool> readToolHistoriesByEntityAndIdentifier(String entity, String identifier) throws IllegalDataAccessException {
		List<Tool> tools = new ArrayList<Tool>();
		try {
			tools = eoJdbcTemplate.query(queryReadToolHistoriesByEntityAndIdentifier, new Object[] { entity, identifier }, new ToolsMapper(identifierDao));
			return tools;
		} catch (DataAccessException e) {
			throw new IllegalDataAccessException(ReturnCodesDataaccess.NO_OBJECTS_FOUND_ERROR.getValue(), e);
		}
	}
}
